package com.entrogy.controller;

import com.entrogy.bean.ParentVisitorEntity;
import com.entrogy.bean.UserEntity;
import com.entrogy.service.ParentService;
import com.entrogy.service.StudentService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.BDFaceDetect;
import com.entrogy.utils.IdGenetor;
import com.entrogy.utils.ZoomImageUtil;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author xlr
 * @date 2019/02/18
 */
@Api(description = "上传图片的接口，老师图片(name=teacher),学生图片(name=student),家长图片(name=parent)共用这个接口。根据传上来的name值来区分存放的位置")
@RestController
@RequestMapping(value = "fileuploadcontroller")
public class FileUploadController {

	private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	//图片存放根路径
	@Value("${image.root.path}")
	private String rootPath;

	@Autowired
	private UserService userService;

	@Autowired
	private ParentService parentService;

	@RequestMapping(value = "upload",method = RequestMethod.POST)
	public Map<String, Object> upload(MultipartFile file, String name, String uid, Integer schoolCode) {
		//返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
		//防止上传空文件导致奔溃
		if (file.isEmpty()) {
			return ApiReturnUtil.error("文件为空");
		}
		//先去判断 图片有没有人脸 或多张人脸
		BufferedImage bufferedImage = null;
		try {
			bufferedImage = ImageIO.read(file.getInputStream());
			bufferedImage = ZoomImageUtil.zoomImage(bufferedImage);
			BDFaceDetect bdFaceDetect = new BDFaceDetect();
			org.json.JSONObject ret = bdFaceDetect.getAvailableBase64(bufferedImage);
			if(ret.getInt("result")==0 || ret.getInt("result")==2 ){//  --0--2代表无人脸、一个人脸、多个人脸
				return ApiReturnUtil.error("亲,您的照片不符合哟");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 获取文件名
		String fileName = IdGenetor.genUUIDFileName() + "_" + file.getOriginalFilename();
		//logger.info("上传的文件名为：" + fileName);
		UserEntity userEntity = (UserEntity) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
		//小程序端采集人像的照片上传的话，schoolCode是有值的
		if (schoolCode == null){
			if (userEntity == null){
				//访客的照片不分学校存储，默认schoolCode为1
				if (uid.startsWith("2")){
					schoolCode = 1;
				}else {
					schoolCode = getSchoolCodeByUserId(uid);
				}
			}else {
				schoolCode = userEntity.getSchoolCode();
			}
		}
		// 设置文件上传后的路径
		String filePath = rootPath + File.separator + schoolCode + File.separator + name;
		//创建文件路径
		File dest = new File(filePath ,fileName);
		// 解决中文问题，liunx下中文路径，图片显示问题
		// fileName = UUID.randomUUID() + suffixName;
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			//假如文件不存在即重新创建新的文件已防止异常发生
			dest.getParentFile().mkdirs();
		}
		try {
			//transferTo（dest）方法将上传文件写到服务器上指定的文件
			file.transferTo(dest);
			logger.info(name + "=>" + schoolCode+File.separator+name+File.separator+fileName);
			return ApiReturnUtil.success("上传成功", schoolCode + File.separator + name + File.separator + fileName);
		} catch (Exception e) {
			return ApiReturnUtil.error("上传失败");
		}
	}

	//获取当前用户的schoolCode
	private Integer getSchoolCodeByUserId(String uid) {
		Integer schoolCode;
		//小程序端无登录功能，首先根据uid到用户表查询schoolCode
		UserEntity user = userService.getUserByUid(uid);
		if(user != null){
			schoolCode = user.getSchoolCode();
		}else {
			//然后根据uid到家长表查询schoolCode
			ParentVisitorEntity parentVisitorEntity = parentService.getparentById(uid);
			schoolCode = parentVisitorEntity.getParentVisitorSchoolCode();
		}
		return schoolCode;
	}

	@RequestMapping(value = "uploadFile",method = RequestMethod.POST)
	public Map<String, Object> upload(MultipartFile file) {
		//返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
		//防止上传空文件导致奔溃
		if (file.isEmpty()) {
			return ApiReturnUtil.error("文件为空");
		}
		// 获取文件名
		String fileName = IdGenetor.genUUIDFileName() + "_" + file.getOriginalFilename();
		// 设置文件上传后的路径
		String filePath = rootPath;
		//创建文件路径
		File dest = new File(filePath ,fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);
			logger.info("正在备份采集的信息。。。");
			return ApiReturnUtil.success("上传成功", "");
		} catch (Exception e) {
			return ApiReturnUtil.error("上传失败");
		}
	}



}
